package com.cloudbroker.bcs.common.validatioin.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.validatioin.annotation.JsonValue;

public class JsonValueValidator implements ConstraintValidator<JsonValue, Object> {
    
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 空值直接通过，由@NotNull之类的控制
        if (null == value || "".equals(value)) {
            return true;
        }
        if (value instanceof String) {
            String str = (String) value;
            try {
                JSONObject.parseObject(str);
            } catch (Exception e) {
                try {
                    JSONObject.parseArray(str);
                } catch (Exception e2) {
                    return false;
                }
            }
            return true;
        } else {
            // 其他类型非法
            return false;
        }
    }
    
    @Override
    public void initialize(JsonValue constraintAnnotation) {
        
    }
    
}
